# pip install uiautomation
import sys, time, re
import uiautomation as auto

TITLE_PATTERNS = [r'.*BOSS直聘.*']            # 标题模糊匹配
CHROME_CLASSES = {'Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'}
MAX_DEPTH = 100
SEARCH_TMO = 3.0
PER_ITEM_TMO = 0.5

def dump_tree(ctrl, depth=0, max_depth=3):
    if depth > max_depth:
        return
    indent = '  ' * depth
    try:
        print(f"{indent}[{depth}] {ctrl.ControlTypeName:12} "
              f"name='{ctrl.Name}' aid='{ctrl.AutomationId}' "
              f"class='{ctrl.ClassName}' rect={ctrl.BoundingRectangle}")
    except Exception:
        print(f"{indent}[{depth}] <error line>")
    try:
        for ch in ctrl.GetChildren():
            dump_tree(ch, depth + 1, max_depth)
    except Exception:
        pass

def list_top_windows():
    root = auto.GetRootControl()
    rows = []
    for w in root.GetChildren():
        try:
            rows.append((w.ControlTypeName, w.Name or '', w.ClassName or '', w))
        except Exception:
            pass
    for i, (t, n, c, _) in enumerate(rows, 1):
        print(f"{i:02d}. type={t:14} name='{n}' class='{c}'")
    return rows

def name_matches(name: str) -> bool:
    return any(re.fullmatch(pat, name or '') for pat in TITLE_PATTERNS)

def pick_boss_root():
    """返回最合理的 BOSS 根节点（Window 或 Pane）"""
    # 1) 先尝试 WindowControl（如果 BOSS 是真正的顶层窗口）
    for pat in TITLE_PATTERNS:
        win = auto.WindowControl(RegexName=pat, searchDepth=1)
        if win.Exists(SEARCH_TMO, 0.2):
            return win

    # 2) 回退：在顶层子控件中找 PaneControl + Class=Chrome_WidgetWin_* + Name 匹配
    tops = list_top_windows()  # 也顺便打印出来方便你核对
    candidates = []
    for _, name, cls, elem in tops:
        if cls in CHROME_CLASSES and name_matches(name):
            candidates.append(elem)

    if candidates:
        # 取面积最大者作为根
        def area(e):
            try:
                r = e.BoundingRectangle
                return max(0, (r.right - r.left)) * max(0, (r.bottom - r.top))
            except Exception:
                return -1
        return max(candidates, key=area)

    return None

def main():
    with auto.UIAutomationInitializerInThread():
        auto.SetGlobalSearchTimeout(PER_ITEM_TMO)

        root = pick_boss_root()
        if not root:
            raise RuntimeError("未找到 BOSS直聘 窗口（尝试 Window 与 Pane 均未命中）。"
                               "请确认标题与列表一致，且脚本与目标程序权限一致。")

        try:
            root.SetActive()
            time.sleep(0.2)
        except Exception:
            pass

        print(f"=== 控件树 (root: type={root.ControlTypeName}, name='{root.Name}', class='{root.ClassName}') ===")
        dump_tree(root, max_depth=MAX_DEPTH)

if __name__ == "__main__":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
    except Exception:
        pass
    main()
